<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>我的好友</title>
  <link rel="stylesheet" href="../static/lib/semantic/semantic.min.css" th:href="@{/lib/semantic/semantic.min.css}">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
  <link rel="stylesheet" href="../static/css/animate.css" th:href="@{/css/animate.css}">
  <link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">
  <style>
      .ui.primary.button[aria-disabled="true"]:hover {
          cursor: not-allowed;
      }

      /* 可选，添加一个禁用图标 */
      .ui.primary.button[aria-disabled="true"] .icon:before {
          content: "\f05e"; /* 这是 FontAwesome 的禁止图标Unicode码，需引入FontAwesome库 */
          color: #c0c0c0; /* 更改图标的颜色以匹配禁用状态 */
      }
  </style>
</head>
<body class="archiveBody">

<!--导航-->
<nav class="gird-header">
  <div class="ui container" style="width: 95%!important;"> <!-- 加一个容器 -->
    <div class="ui inverted secondary stackable menu"> <!-- 菜单 stackable:可堆叠的,表示屏幕小时自动堆叠-->
      <a th:href="@{/user_index}"><h2 class="ui white header item">GuideSystem</h2></a> <!-- 蓝绿色标题 -->
      <a href="#" th:href="@{/user_index}" class="m-item m-mobile-hide item"><i class="home icon"></i>首页</a>
      <!-- icon表示图标 -->
      <a href="#" th:href="@{/user_forum}" class="m-item m-mobile-hide item"><i class="comments icon"></i>论坛</a>
      <a href="#" th:href="@{/user_types/-1}" class="m-item m-mobile-hide item"><i class="idea icon"></i>分类</a>
      <a href="#" th:href="@{/about}" class="m-item m-mobile-hide item"><i class="info icon"></i>我的</a>
      <div class="m-top-right m-mobile-hide item m-item" style="margin: auto; margin-top: -5px;"> <!-- 靠右 -->
        <form name="search" method="get" action="#" th:action="@{/user_search}" target="_blank">
          <div class="ui icon input">
            <input type="text" name="query" placeholder="Search..." th:value="${query}">
            <i onclick="document.forms['search'].submit()" class="search link icon"></i>
          </div>
        </form>
        <div class="ui dropdown item">
          <div class="container">
            <img src="../static/images/店铺1.jpg" th:src="@{${session.user?.avatar}}" alt="" class="ui avatar image"
                 style="object-fit: cover;
                       outline: 0px;
                       background-size: 100% 100%;">
          </div>
          <i class="dropdown icon"></i>
          <div class="menu">
            <a href="#" th:href="@{/about}" target="_blank" class="item">我的</a>
            <a href="#" th:href="@{/edit/password}" class="item">修改密码</a>
            <a href="#" th:href="@{/login/exit}" id="logout-link" class="item">退出</a>
            <a href="#" onclick="deleteAccount()" class="item">注销</a> <!--得更新-->
          </div>
          <input type="hidden" name="concurrentId" th:value="${session.user?.id}"/>
          <input type="hidden" name="concurrentUsername" th:value="${session.user?.username}"/>
          <input type="hidden" name="concurrentAvatar" th:value="${session.user?.avatar}"/>
          <input type="hidden" name="concurrentNickname" th:value="${session.user?.nickname}"/>
          <input type="hidden" name="concurrentDescription" th:value="${session.user?.description}"/>
        </div>
      </div>
    </div>
  </div>
  <a href="#" class="ui menu toggle black button icon m-top-right m-mobile-show">
    <i class="sidebar icon"></i>
  </a>
</nav>

<div class="ui m-container-plus m-margin-top-large animate__fadeIn" id="appMain"
     style="padding-bottom: 2em !important; margin-top: 5em !important;">
  <div class="ui stackable grid">
    <div class="eleven wide column">
      <div class="ui container transparent-segment segment m-margin-buttom-large">
        <!-- 数据统计 -->
        <div class="ui three statistics" style="margin-top: 40px">
          <div class="statistic">
            <div class="value">
              <a id="hottest" v-if="friendHottest.userId != 0" @click="showHottest">
                <img :src="friendHottest.avatar" class="ui circular inline image" style="cursor: pointer;">
              </a>
              <img src="https://sky-take-out-kafka.oss-cn-beijing.aliyuncs.com/defaultAvatar.png"
                   style="max-height: 4rem!important;" v-else>
            </div>
            <div class="label">聊得最热</div>
          </div>
          <div class="statistic">
            <div class="value">
              <a @click="chatOften">
                <i class="users inline icon" style="cursor: pointer;"></i>
              </a>
            </div>
            <div class="label">最近常聊</div>
          </div>
          <div class="statistic">
            <div class="value">{{friendsNumber}}</div>
            <div class="label">好友成员</div>
          </div>
        </div>

        <br>
        <div class="ui horizontal divider">好友列表</div>

        <!-- 好友列表 -->
        <div class="ui items">
          <div class="item" v-for="friend in pageFriends" style="max-height: 80px">
            <a class="ui tiny image" :href="'/dev/userOtherAbout/' + friend.userId" target="_blank">
              <img :src="friend.avatar"
                   style="object-fit: cover;
                       cursor: pointer;
                       outline: 0px;
                       max-height: 80px;
                       height: 80px;
                       background-size: 100% 100%;">
            </a>
            <div class="content">
              <a class="header" :href="'/dev/userOtherAbout/' + friend.userId" target="_blank">{{friend.nickname}}</a>
              <div class="description">
                <!--<p>Stevie Feliciano is a <a>library scientist</a> living in New York City. She likes to spend her time
                  reading, running, and writing.</p>-->
                <p v-if="friend.description.length > 80">{{friend.description.slice(0, 80)}}...</p>
                <p v-else>{{friend.description}}</p>
              </div>
              <a class="header" :href="'/dev/chat/' + friend.userId" target="_blank" style="float: right;">
                <div class="ui basic mini right floated button"
                     style="font-weight: bold!important; margin-top: 5px!important;">
                  <i class="wechat icon"></i>
                  聊天
                </div>
              </a>
              <a class="header" :href="'/dev/userOtherAbout/' + friend.userId" target="_blank" style="float: right;">
                <div class="ui basic mini right floated button"
                     style="font-weight: bold!important; margin-top: 5px!important;">
                  <i class="mouse pointer icon"></i>
                  主页
                </div>
              </a>
            </div>
          </div>
          <!--/*-->
          <div class="item">
            <a class="ui tiny image">
              <img src="../static/images/avatar/joe.jpg">
            </a>
            <div class="content">
              <a class="header">Veronika Ossi</a>
              <div class="description">
                <p>Veronika Ossi is a set designer living in New York who <a>enjoys</a> kittens, music, and partying.
                </p>
              </div>
            </div>
          </div>
          <!--*/-->

          <!-- 分页容器 -->
          <div class="ui grid container" style="margin-top: 0rem;">
            <div class="center aligned column">
              <!-- 分页板块1 -->
              <div class="ui pagination menu" v-if="totalPages <= 6">
                <a href="#" class="item" @click.prevent="goToPage(currentPage - 1)"
                   :class="{ disabled: currentPage === 1 }">上一页</a>
                <a href="#"
                   v-for="pageNumber in totalPages"
                   :key="pageNumber"
                   class="item"
                   @click.prevent="goToPage(pageNumber)"
                   :class="{ active: pageNumber === currentPage }">{{ pageNumber }}</a>
                <a href="#" class="item" @click.prevent="goToPage(currentPage + 1)"
                   :class="{ disabled: currentPage === totalPages }">下一页</a>
              </div>

              <!-- 分页板块2 -->
              <div class="ui pagination menu" v-else>
                <a href="#" class="item" @click.prevent="goToPage(currentPage - 1)"
                   :class="{ disabled: currentPage === 1 }">上一页</a>
                <!-- 如果不是第一页且当前页在前三页，显示连续页码 -->
                <a href="#"
                   v-for="pageNumber in [1, 2, 3]"
                   :key="pageNumber"
                   class="item"
                   @click.prevent="goToPage(pageNumber)"
                   :class="{ active: pageNumber === currentPage }">{{ pageNumber }}</a>

                <!-- 当前页码与总页数之间的页码处理 -->
                <template v-if="currentPage > 3 && currentPage < totalPages - 1">
                  <!-- 显示省略号 -->
                  <a class="item">...</a>
                  <!-- 显示当前页码以及前后各1个页码 -->
                  <a href="#"
                     :key="currentPage"
                     class="item"
                     @click.prevent="goToPage(currentPage)"
                     :class="{ active: true }">{{ currentPage }}</a>
                  <!-- 显示省略号 -->
                  <a class="item">...</a>
                </template>
                <template v-else>
                  <a class="item">...</a>
                </template>

                <!-- 如果不是最后几页，显示连续页码 -->
                <a href="#"
                   v-for="pageNumber in [totalPages - 1, totalPages]"
                   :key="pageNumber"
                   class="item"
                   @click.prevent="goToPage(pageNumber)"
                   :class="{ active: pageNumber === currentPage }">{{ pageNumber }}</a>

                <a href="#" class="item" @click.prevent="goToPage(currentPage + 1)"
                   :class="{ disabled: currentPage === totalPages }">下一页</a>
              </div>

              <!-- 跳转至指定页输入框 -->
              <div class="ui action input">
                <input type="number" min="1" max="totalPages" v-model="jumpToPage" placeholder="输入页码..."
                       style="width: 110px;
                       height: 41px;
                       padding-top: 0.5em;">
                <button class="ui button" @click.prevent="goToJumpedPage" :disabled="!isValidPage(jumpToPage)">跳转
                </button>
              </div>

            </div>
          </div>

        </div>

        <div class="ui search m-top-right" style="margin-right: 15px; margin-top: 10px">
          <div class="ui icon input">
            <input class="prompt" type="text" v-model="searchMyFriends" placeholder="搜索我的好友...">
            <i class="search icon"></i>
          </div>
        </div>
      </div>

    </div>

    <div class="five wide column">
      <!--申请列表-->
      <div class="ui container transparent-segment segment" v-if="applyList.length > 0">
        <div class="ui relaxed list">
          <div class="item" v-for="(apply, index) in applyList">
            <img class="ui avatar image" :src="apply.senderAvatar"
                 style="object-fit: cover;
                       cursor: pointer;
                       outline: 0px;
                       background-size: 100% 100%;">
            <div class="content" style="padding: 5px">
              <a class="header" :href="'/dev/userOtherAbout/' + apply.senderId" target="_blank">
                <p v-if="apply.senderNickname.length > 12">{{apply.senderNickname.slice(0, 12)}}...</p>
                <p v-else>{{apply.senderNickname}}</p>
              </a>
            </div>
            <button class="ui basic mini right floated button" style="font-weight: bold; margin: 0em;"
                    @click="agreeApply(apply)">
              <i class="icon thumbs up"></i>
              同意
            </button>
            <button class="ui basic mini right floated button"
                    style="font-weight: bold; margin-right: 0.2em; margin-left: 0;"
                    @click="rejectApply(apply.id)">
              <i class="icon thumbs down"></i>
              拒绝
            </button>
          </div>
          <!--/*-->
          <div class="item">
            <img class="ui avatar image" src="../static/images/avatar/joe.jpg">
            <div class="content" style="padding: 6px">
              <a class="header"><p>Feliciano</p></a>
            </div>
            <button class="ui basic mini right floated button" style="font-weight: bold!important;">
              <i class="icon user"></i>
              同意
            </button>
          </div>
          <!--*/-->
        </div>
      </div>
      <!--足迹展示-->
      <div class="ui container transparent-segment segment">
        <div class="ui relaxed list">
          <div class="item" v-if="commentMax">
            <img class="ui avatar image" :src="commentMax.avatar">
            <div class="content">
              <a class="header" :href="'/dev/userOtherAbout/' + commentMax.userId"
                 target="_blank">{{commentMax.nickname}}</a>
              <div class="description">最近评论你的帖子最多。</div>
              <p>达到 <span style="color: #d27b53; font-weight: bold">{{commentMax.count}}</span> 条</p>
            </div>
          </div>
          <div class="item" v-if="collectionMax">
            <img class="ui avatar image" :src="collectionMax.avatar">
            <div class="content">
              <a class="header" :href="'/dev/userOtherAbout/' + collectionMax.userId"
                 target="_blank">{{collectionMax.nickname}}</a>
              <div class="description">最近收藏你的帖子最多。</div>
              <p>达到 <span style="color: #d27b53; font-weight: bold">{{collectionMax.count}}</span> 篇</p>
            </div>
          </div>
          <div class="item" v-if="viewMax">
            <img class="ui avatar image" :src="viewMax.avatar">
            <div class="content">
              <a class="header" :href="'/dev/userOtherAbout/' + viewMax.userId"
                 target="_blank">{{viewMax.nickname}}</a>
              <div class="description">一直以来访问你的
                <a :href="'/dev/about'" target="_blank"><b>主页</b></a> 最多。
                <p>达到 <span style="color: #d27b53; font-weight: bold">{{viewMax.count}}</span> 次</p>
              </div>
            </div>
          </div>
        </div>
        <div class="ui horizontal divider">end</div>
        <button class="ui primary button" @click="addFriend">
          添加好友
        </button>
        <button class="ui right floated button" @click="deleteFriend">
          删除好友
        </button>
      </div>
    </div>

  </div>

  <!--聊得最热模态框-->
  <div class="ui hottest modal">
    <i class="close icon"></i>
    <div class="header">
      聊得最热
    </div>
    <div class="image content">
      <div class="ui small image">
        <img :src="friendHottest.avatar" style="width: 150px">
      </div>
      <div class="description">
        <div class="ui header">{{friendHottest.nickname}}</div>
        <p>{{friendHottest.description}}</p>
      </div>
    </div>
    <div class="actions">
      <a :href="'/dev/userOtherAbout/' + friendHottest.userId" target="_blank">
        <div class="ui black deny icon button">
          查看主页
        </div>
      </a>
      <a :href="'/dev/chat/' + friendHottest.userId" target="_blank">
        <div class="ui positive right icon button">
          找Ta聊天
        </div>
      </a>
    </div>
  </div>

  <!--最近常聊模态框-->
  <div class="ui chatOften modal">
    <i class="close icon"></i>
    <div class="header">
      最近常聊
    </div>
    <div class="ui large aligned divided list" style="margin: 0px" v-if="friendListOften.length > 0">
      <div class="item centering example" style="padding: 10px" v-for="friend in friendListOften">
        <div class="right floated content">
          <a :href="'/dev/userOtherAbout/' + friend.userId" target="_blank">
            <div class="ui icon button">查看主页</div>
          </a>
          <a :href="'/dev/chat/' + friend.userId" target="_blank">
            <div class="ui blue icon button">找Ta聊天</div>
          </a>
        </div>
        <img class="ui avatar image example tip" :src="friend.avatar"
             style="object-fit: cover;
             cursor: pointer;
             outline: 0px;
             background-size: 100% 100%;">
        <div class="content" style="padding: 6px !important;">
          {{friend.nickname}}
        </div>
      </div>
      <!--/*-->
      <div class="item" style="padding: 10px">
        <div class="right floated content">
          <div class="ui icon button">查看主页</div>
          <div class="ui blue icon button">找Ta聊天</div>
        </div>
        <img class="ui avatar image" src="../static/images/avatar/justen.jpg">
        <div class="content">
          Lindsay
        </div>
      </div>
      <div class="item" style="padding: 10px">
        <div class="right floated content">
          <div class="ui icon button">查看主页</div>
          <div class="ui blue icon button">找Ta聊天</div>
        </div>
        <img class="ui avatar image" src="../static/images/avatar/joe.jpg">
        <div class="content">
          Mark
        </div>
      </div>
      <div class="item" style="padding: 10px">
        <div class="right floated content">
          <div class="ui icon button">查看主页</div>
          <div class="ui blue icon button">找Ta聊天</div>
        </div>
        <img class="ui avatar image" src="../static/images/avatar/joe.jpg">
        <div class="content">
          Molly
        </div>
      </div>
      <!--*/-->
    </div>
    <div class="ui icon message" style="background-color: #f1f1f1; margin: auto" v-else>
      <i class="info circle icon"></i>
      <div class="content">
        <div class="header">你的常聊列表为空</div>
        <p>最近一个月，你还没有和朋友聊过天，快去畅聊吧(*´▽｀)ノノ</p>
      </div>
    </div>
  </div>

  <!--添加好友模态框-->
  <div class="ui addFriend modal">
    <i class="close icon"></i>
    <div class="header">
      添加好友
    </div>
    <div class="ui search m-top-right" style="margin-right: 15px; margin-top: 12px">
      <!-- 添加Semantic UI的错误消息 -->
      <transition name="fade">
        <div class="ui right pointing red basic label transition visible" v-if="showErrorMessage">
          {{ errorMessage }}
        </div>
      </transition>
      <div class="ui icon input">
        <input class="prompt" type="text" v-model="searchText" placeholder="搜索好友...">
        <button class="ui button" style="background-color: transparent"><i class="search icon" @click="doSearch"></i>
        </button>
      </div>
    </div>
    <div class="ui m-container m-margin-tb-large m-margin-lr-large">
      <div class="ui four doubling stackable cards" id="card-container">
        <!-- 动态卡片模板 -->
        <template id="card-template" v-if="searchFriends.length > 0">
          <div class="ui card" v-for="friend in searchFriends">
            <div class="image">
              <img :src="friend.avatar" alt="Card Image"
                   style="object-fit: cover;
                   outline: 0px;
                   height: 135px;
                   background-size: 100% 100%;">
            </div>
            <div class="content">
              <div class="header">{{friend.nickname}}</div>
              <div class="description">{{friend.signature}}</div>
            </div>
            <div class="extra content">
              <div class="ui primary button" v-if="friend.me == true" aria-disabled="true" disabled>本人</div>
              <div class="ui primary button" v-else-if="friend.friend == true" aria-disabled="true" disabled>
                已添加
              </div>
              <div class="ui primary button" @click="doAdd(friend)" v-else>添加</div>
              <a :href="'/dev/about'" target="_blank" v-if="friend.me == true">
                <div class="ui button">主页</div>
              </a>
              <a :href="'/dev/userOtherAbout/' + friend.userId" target="_blank" v-else>
                <div class="ui button">主页</div>
              </a>
            </div>
          </div>
        </template>
        <div class="ui icon message" v-else>
          <i class="notched circle loading icon"></i>
          <div class="content">
            <div class="header">等待搜索中</div>
            <p>请在搜索框输入要查找的关键字，我们将为您获取内容。</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!--删除好友模态框-->
  <div class="ui deleteFriend modal">
    <i class="close icon"></i>
    <div class="header">
      删除好友
    </div>
    <div class="ui large aligned divided list" style="margin: 0px" v-if="friendList.length > 0">
      <div class="item centering example" style="padding: 10px" v-for="friend in friendList">
        <div class="right floated content">
          <a :href="'/dev/userOtherAbout/' + friend.userId" target="_blank">
            <div class="ui icon button">查看主页</div>
          </a>
          <div class="ui yellow icon button" @click="doDelete(friend.userId)">删除Ta</div>
        </div>
        <img class="ui avatar image" :src="friend.avatar"
             style="object-fit: cover;
             outline: 0px;
             background-size: 100% 100%;">
        <div class="content" style="padding: 6px !important;">
          {{friend.nickname}}
        </div>
      </div>
    </div>
    <div class="ui icon message" style="background-color: #f1f1f1; margin: auto" v-else>
      <i class="info circle icon"></i>
      <div class="content">
        <div class="header">你的好友列表为空</div>
        <p>你还没有好友哦，尝试添加好友吧(*´▽｀)ノノ</p>
      </div>
    </div>
  </div>

</div>

<!--确认删除-->
<div class="ui tiny modal">
  <i class="close icon"></i>
  <div class="header">
    好友删除
  </div>
  <div class="content">
    <div class="description" name="descriptionDel">
      确定要删除该好友嘛？关于Ta的所有记录将会保留30天哦~
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDel">
      确认
    </button>
    <button class="ui cancel button" id="cancelDel">
      取消
    </button>
  </div>
</div>

<!--确认注销-->
<div th:fragment="destroyAccount" class="ui destroy modal">
  <i class="close icon"></i>
  <div class="header">
    账号注销
  </div>
  <div class="content">
    <div class="ui form warning">
      <div class="field">
        <label>确认密码</label>
        <input type="password" name="password" placeholder="请输入密码...">
      </div>
      <div class="ui warning message">
        <div class="header">注销提醒！</div>
        <ul class="list">
          <li>只有填入你的账号密码, 你才能注销帐号</li>
          <li>注销账号, 意味着你的账号信息全部清空</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDestroy">
      确认
    </button>
    <button class="ui cancel button">
      取消
    </button>
  </div>
</div>

<script src="../static/js/vue.js" th:src="@{/js/vue.js}"></script>
<script src="../static/js/axios-0.18.0.js" th:src="@{/js/axios-0.18.0.js}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="../static/lib/semantic/semantic.min.js" th:src="@{/lib/semantic/semantic.min.js}"></script>
<!--<script src="https://fastly.jsdelivr.net/gh/stevenjoezhang/live2d-widget/autoload.js"></script>-->
<script>

    $('.ui.dropdown').dropdown({
        on: 'hover'
    });

    // 绑定退出按钮的点击事件
    $('#logout-link').on('click', function (event) {
        // 清除 sessionStorage
        window.sessionStorage.clear();
    });

    function deleteAccount() {
        $('.destroy.modal').modal('show');

        $('#confirmDestroy').click(async () => {
            var searchParams = new URLSearchParams();
            searchParams.append("password", $("[name='password']").val());

            const response = await fetch("/dev/login/delete", {
                method: 'POST',
                redirect: 'follow', // 允许fetch跟随重定向
                body: searchParams
            });
            const data = await response.json();
            console.log(data)
            if (data.status === "error") {
                alert(data.message);
                window.location.href = data.redirectUrl;
            } else if (data.status === "success") {
                alert(data.message);
                // 重定向到指定URL
                window.location.href = data.redirectUrl;
            }
        })
    }

    const cId = $("[name='concurrentId']").val();
    const cUsername = $("[name='concurrentUsername']").val();
    const cAvatar = $("[name='concurrentAvatar']").val();
    const cDescription = $("[name='concurrentDescription']").val();
    const cNickname = $("[name='concurrentNickname']").val();

    // Axios 是异步发送 HTTP 请求的, 那么我们应该将请求方法标记为异步，并使用 await 关键字等待 Axios 请求完成。
    new Vue({
        el: "#appMain",
        data() {
            return {
                userUsername: cUsername,
                userId: cId,
                userAvatar: cAvatar,
                userDescription: cDescription,
                userNickname: cNickname,
                friendsNumber: 0,
                viewMax: null,
                collectionMax: null,
                commentMax: null,
                searchText: "",
                showErrorMessage: false,
                errorMessage: '输入内容不能为空',
                searchFriends: [],
                friendHottest: { // fromName、sendTime等在服务端获取
                    userId: 0,
                    username: "",
                    avatar: "",
                    description: "",
                    nickname: ""
                },
                friendListOften: [],
                friendList: [], // 原始好友列表
                filteredFriends: [], // 过滤后的可见好友列表
                // pageFriends: [], // 过滤后的分页列表
                applyList: [],
                searchMyFriends: '',
                currentPage: 1, // 当前页数
                pageSize: 10, // 每页显示的好友数量
                jumpToPage: '', //跳转分页
                // totalPages: 10, // 总页数
            }
        },
        created() { // new这个Vue对象时会自动执行
            this.init();
            // console.log(this.filteredFriends); // 这个会被先执行(先于this.getFriendList()，原因未知...)
            console.log("初始化Vue.");
        },
        watch: {
            // 监听搜索输入
            searchMyFriends(newVal) {
                this.filteredFriends = this.friendList.filter(friend => {
                    return friend.nickname.toLowerCase().includes(newVal.toLowerCase());
                });
            },
        },
        // 计算属性(先create再computed，但是data属性变化跟不上computed计算: filteredFriends、currentPage、pageSize一旦变化便重新计算pageFriends、totalPages)
        /*
                根据Vue.js的计算属性特性，每当依赖于pageFriends和totalPages计算结果的任何底层数据发生变化时
                (在这里是filteredFriends和currentPage，也可能包括pageSize)，Vue将会自动且高效地重新计算这些计算属性的值。
                因为计算属性的结果是基于它们的响应式依赖关系（所依赖的data属性）缓存的，并会在相关依赖发生改变时得到更新。
        */
        computed: {
            pageFriends() {
                var data = this.filteredFriends.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                console.log(data);
                return data;
            },
            totalPages() {
                var totalPages = this.filteredFriends ? Math.ceil(this.filteredFriends.length / this.pageSize) : 0;
                console.log(totalPages);
                return totalPages;
            }
        },
        methods: {
            // 初始化方法
            async init() {
                await this.getFriendList();
                await this.getApplys();
                await this.showFootprint();
                await this.getFriendsNumber();
                await this.hottest();
            },
            // 获取好友列表
            async getFriendList() {
                await axios.get("list").then(res => {
                    this.filteredFriends = res.data;
                    this.friendList = res.data;
                });
            },
            // 列表分页
            goToPage(pageNum) {
                if (pageNum >= 1 && pageNum <= this.totalPages) {
                    this.currentPage = pageNum;
                    // 取当前分页好友列表
                    // this.filteredFriends.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
            },
            // 跳转分页
            goToJumpedPage() {
                const targetPage = parseInt(this.jumpToPage);
                if (targetPage > 0 && targetPage <= this.totalPages) {
                    this.currentPage = targetPage;
                    this.jumpToPage = '';
                }
            },
            // 校验跳转是否合理
            isValidPage(page) {
                return !isNaN(page) && page > 0 && page <= this.totalPages;
            },
            // 最热好友
            async hottest() { // 写法一
                await axios.get("hottest").then(res => {
                    if (res.data) this.friendHottest = res.data;
                });
            },
            // 展示最热模态框
            showHottest() {
                $('.ui.hottest.modal').modal('show');
            },
            /*chatOften: () => { // 写法二(匿名回调函数写法，第一次请求得到的数据无法传给friendListOften，这种写法不行)
                $('.ui.chatOften.modal').modal('show');
                axios.get("often").then(res => {
                    this.friendListOften = res.data;
                });
            },*/
            // 常聊好友
            async chatOften() {
                await axios.get("often").then(res => {
                    this.friendListOften = res.data;
                });
                $('.ui.chatOften.modal').modal('show');
            },
            // 展示添加模态框
            addFriend: function () { // 写法三
                $('.ui.addFriend.modal').modal('show');
            },
            // 搜索好友
            async doSearch() {
                if (this.searchText.trimEnd() == "") {
                    this.showErrorMessage = true;
                    setTimeout(() => {
                        this.showErrorMessage = false;
                    }, 2000);
                    this.searchText = "";
                    return;
                }
                await axios.get("search?keyword=" + this.searchText).then(res => {
                    this.searchFriends = res.data;
                });
                console.log(this.searchFriends);
                this.searchText = "";
            },
            // 添加好友(发起好友申请)
            async doAdd(friend) {
                let apply = {
                    id: null,
                    senderId: this.userId,
                    recipientId: friend.userId,
                    senderNickname: this.userNickname,
                    senderAvatar: this.userAvatar,
                    applyTime: new Date()
                };
                await axios.post("apply/add", apply, {
                    // 请求体apply对象为JSON格式
                    headers: {
                        "Content-Type": "application/json"
                    },
                });
                await this.getApplys();
                $('.ui.addFriend.modal').modal('hide');
                this.searchFriends = [];
            },
            // 展示删除模态框
            deleteFriend() {
                $('.ui.deleteFriend.modal').modal('show');
            },
            // 删除好友
            async doDelete(id) {
                $('.tiny.modal').modal('show');

                let confirmed = new Promise((resolve, reject) => {
                    const confirmButton = $('#confirmDel');
                    const cancelButton = $('#cancelDel');
                    confirmButton.one('click', () => {
                        resolve();
                    });
                    cancelButton.one('click', () => {
                        // 取消删除逻辑
                    });
                });

                // 点击confirmDel按钮才执行try
                await confirmed;
                try {
                    await axios.delete("delete/" + id);
                    await this.getFriendList();
                    await this.getFriendsNumber();
                    await this.hottest();
                    $('.tiny.modal').modal('hide');
                    $('.ui.deleteFriend.modal').modal('hide');
                } finally {
                    // 其他逻辑
                }

            },
            // 用户足迹展示
            async showFootprint() {
                await axios.get("about/viewMax").then(res => {
                    if (res.data) this.viewMax = res.data; // if等效于res.data != null && res.data != undefined
                });
                await axios.get("blog/collectionMax").then(res => {
                    if (res.data) this.collectionMax = res.data;
                });
                await axios.get("blog/commentMax").then(res => {
                    if (res.data) this.commentMax = res.data;
                });
            },
            // 获取好友申请
            async getApplys() {
                await axios.get("apply/list").then(res => {
                    this.applyList = res.data;
                });
            },
            async getFriendsNumber() {
                await axios.get("count").then(res => {
                    this.friendsNumber = res.data;
                });
            },
            // 同意好友申请(添加到通讯录)
            async agreeApply(apply) {
                let friend = {
                    id: null,
                    user1Id: apply.recipientId, // user1是当前用户
                    user2Id: apply.senderId, // user2是好友申请者
                    user1Nickname: this.userNickname,
                    user2Nickname: "",
                    user1Username: this.userUsername,
                    user2Username: "",
                    user1Avatar: this.userAvatar,
                    user2Avatar: "",
                    user1Description: this.userDescription,
                    user2Description: ""
                };
                await axios.post("add?applyId=" + apply.id, friend, {
                    // 请求体对象为JSON格式
                    headers: {
                        "Content-Type": "application/json"
                    },
                });
                await this.getApplys();
                await this.getFriendList();
                await this.getFriendsNumber();
            },
            async rejectApply(id) {
                await axios.delete("apply/delete/" + id);
                await this.getApplys();
            }
        }
    });

</script>

</body>
</html>